package com.jt.redis.resource.controller;

import com.jt.redis.resource.annotation.RequiredLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
//@CrossOrigin
@RestController
@RequestMapping("/resource")
public class ResourceController {
    @Value("${jt.resource.path:D:/CBGIV/RESOURCE/uploads}")
    private String resourcePath;
    @Value("${jt.resource.host:http://localhost:8881}")
    private String resourceHost;
    @RequiredLog("uploadFile")
    /*登录后，必须有@PreAuthorize("hasAnyAuthority('sys:res:create')")权限才可以进行上传
    .antMatchers("/resource/upload").authenticated()*/
    @PreAuthorize("hasAnyAuthority('sys:res:create')")
    @PostMapping("/upload")
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        //创建时间分割的文件储存目录空间
        String dateDir = DateTimeFormatter.ofPattern("/yyyy/MM/dd/").format(LocalDate.now());
        //构建目录文件对象
        File pathDateDir = new File(resourcePath, dateDir);
        //判断文件是否存在
        if(!pathDateDir.exists())pathDateDir.mkdirs();
        //拼接新文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String ext = uploadFile.getOriginalFilename()
                .substring(uploadFile.getOriginalFilename().lastIndexOf("."));
        String newFileName = uuid+ext;
        //上传文件
        File file = new File(pathDateDir, newFileName);
        uploadFile.transferTo(file);
        //拼接网络访问地址
        String url = resourceHost+dateDir+newFileName;
        return url;
    }
    @GetMapping("/get")
    public String getPath(){
        log.trace( "trace");
        log.debug("debug");
        log.info("info");
        log.warn("warn");
        log.error("error");
        return resourcePath+"\n"+resourceHost;
    }
}
